import { ref } from 'vue'

interface SubtitleSegment {
    number: number;
    startTime: string;
    endTime: string;
    text: string;
  }

// 定义一个接口来描述每个段落的结构 用来接收字幕生成的数据
interface SegmentInfo {
    index: number;
    text: string;
    duration: number;
  }
  
export function Dsubtitles() {

      
    function Titlegeneration(text: string): SubtitleSegment[] {
        // 在这里实现字幕生成逻辑
        const subtitles: SubtitleSegment[] = [];
        // ... 添加字幕生成代码 ...
        return subtitles;
      }


    ///字幕下载
    function Captioning(text: any): string {  // 返回类型为 SubtitleSegment 数组


        return "";
    }

    ///字幕合成
    function Captioncomposition(segments: SegmentInfo[], audioUrlall: string): string {
        let srtContent = '';
        let currentTime = 0;
        let lastEndTime = 0; // 用于存储上一个字幕的结束时间
        let subtitleIndex = 1;
        let fileName = audioUrlall.split('/').pop()?.split('.')[0] || 'subtitles';
    
        segments.forEach((segment) => {
            const segmentDuration = segment.duration;
            const sentences = segment.text.split(/[。！？，：；.!?,;:\n]+/).filter(s => s.trim() !== '');
            const totalChars = sentences.reduce((sum, s) => sum + s.trim().length, 0);
            const timePerChar = segmentDuration / totalChars;
    
            let segmentStartTime = currentTime;
            let remainingDuration = segmentDuration;
    
            sentences.forEach((sentence, index) => {
                const text = sentence.trim();
                let duration;
                if (index === sentences.length - 1) {
                    duration = remainingDuration;
                } else {
                    duration = text.length * timePerChar;
                    duration = Number(duration.toFixed(6));
                }
    
                // 确保当前字幕的开始时间不早于上一个字幕的结束时间
                if (segmentStartTime < lastEndTime) {
                    segmentStartTime = lastEndTime + 0.01; // 增加一个小的时间间隔
                }
    
                const startTime = formatTime(segmentStartTime);
                segmentStartTime += duration;
                remainingDuration -= duration;
                const endTime = formatTime(segmentStartTime);
    
                srtContent += `${subtitleIndex}\n`;
                srtContent += `${startTime} --> ${endTime}\n`;
                srtContent += `${text}\n\n`;
    
                subtitleIndex++;
                lastEndTime = segmentStartTime; // 更新上一个字幕的结束时间为当前的结束时间
            });
    
            currentTime += segmentDuration;
        });
    
        const blob = new Blob([srtContent], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${fileName}.srt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    
        return srtContent;
    }
    
// 更新时间格式化函数，增加精度
function formatTime(seconds: number): string {
    // 确保秒数不会出现负数
    seconds = Math.max(0, seconds);
    
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);
    const ms = Math.floor((seconds % 1) * 1000);

    return `${String(hours).padStart(2, '0')}:${
        String(minutes).padStart(2, '0')}:${
        String(secs).padStart(2, '0')},${
        String(ms).padStart(3, '0')}`;
}
    // 其他音频相关的方法...

    return {
        Titlegeneration,
        Captioning,
        Captioncomposition
        // 返回其他需要在组件中使用的变量和方法
    }
}